/* t_time.c : test dgnsc time
 * Copyright (C) 2009-2010 drangon <drangon.zhou@gmail.com>
 * 2009-05
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <dgnsc/common.h>

#include <stdio.h>

#ifdef _WIN32
#include <windows.h>
#endif

int main( int argc, char * argv[] )
{
	int64_t now, now2;
	now = dgn_time_now();
	dgn_sleepms( 5 );
	now2 = dgn_time_now();
	
	int year, month, day, hour, min, sec, usec;
	dgn_time_to( now, &year, &month, &day, &hour, &min, &sec, &usec );

	int64_t ts;
	ts = dgn_time_from( year, month, day, hour, min, sec, usec + 1 );

	printf( "now %d.%06d, %d.%06d, now2 %d.%06d\n", 
			(int)(now / 1000000LL), (int)(now % 1000000LL),
			(int)(ts / 1000000LL), (int)(ts % 1000000LL),
			(int)(now2 / 1000000LL), (int)(now2 % 1000000LL) );
	printf( "%4d-%02d-%02d %02d:%02d:%02d.%06d\n", year, month, day, hour, min, sec, usec );

	int64_t t1, t2;
	t1 = dgn_time_tick();
	dgn_sleepms( 5 );
	t2 = dgn_time_tick();
	printf( "sleep 5, diff %d, t1 %d.%06d, t2 %d.%06d\n", (int)(t2 - t1), 
			(int)(t1 / 1000000LL), (int)(t1 % 1000000LL),
			(int)(t2 / 1000000LL), (int)(t2 % 1000000LL) );
	t1 = dgn_time_tick();
	dgn_sleepms( 23 );
	t2 = dgn_time_tick();
	printf( "sleep 23, diff %d, t1 %d.%06d, t2 %d.%06d\n", (int)(t2 - t1), 
			(int)(t1 / 1000000LL), (int)(t1 % 1000000LL),
			(int)(t2 / 1000000LL), (int)(t2 % 1000000LL) );

#ifdef _WIN32
	// test timer, timeGetTime() precision 15ms, Sleep() 15ms
	TIMECAPS tc;
	timeGetDevCaps( &tc, sizeof(tc) );
//	printf( "timeGetCaps return %d, %d\n", tc.wPeriodMin, tc.wPeriodMax );
	LARGE_INTEGER freq, tt1, tt2;
	QueryPerformanceFrequency( &freq );
	timeBeginPeriod( 1 );
	int t3, t4;
	int i, j, m;
	for( i = 1; i < 40; i++ ) {
		t3 = timeGetTime();
		QueryPerformanceCounter( &tt1 );
		//	Sleep( i );
		for( m = 0, j = 0; j < 100000 * i; j++ )
			m += j;
		QueryPerformanceCounter( &tt2 );
		t4 = timeGetTime();
		timeEndPeriod( 1 );
		// printf( "t3 %d, t4 %d, perf diff %d, m %d\n", t3, t4, (int)((tt2.QuadPart - tt1.QuadPart) * 1000000LL / freq.QuadPart), m );
	}
#endif // _WIN32

	return 0;
}

